{% extends "base.html" %}

{% block title %}{% if object %}编辑用户{% else %}创建用户{% endif %} - Django管理平台{% endblock %}
{% block description %}{% if object %}编辑现有用户信息{% else %}创建新用户并设置权限{% endif %}{% endblock %}

{% block extra_css %}
<style>
    .form-container {
        max-width: 600px;
        margin: 0 auto;
        animation: fadeIn 0.3s ease-out;
    }
    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: translateY(10px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
    .card {
        background-color: white;
        border-radius: 0.5rem;
        box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
        margin-bottom: 1.5rem;
    }
    .form-group {
        margin-bottom: 1.5rem;
    }
    .form-label {
        display: block;
        margin-bottom: 0.5rem;
        font-weight: 500;
        color: #374151;
    }
    .form-control {
        width: 100%;
        padding: 0.5rem 1rem;
        border: 1px solid #e5e7eb;
        border-radius: 0.375rem;
        font-size: 0.875rem;
        transition: all 0.2s ease;
    }
    .form-control:focus {
        outline: none;
        border-color: #3b82f6;
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
    }
    .form-control.error {
        border-color: #ef4444;
    }
    .form-error {
        color: #ef4444;
        font-size: 0.75rem;
        margin-top: 0.25rem;
    }
    .checkbox-group {
        display: flex;
        align-items: center;
        margin-bottom: 1rem;
    }
    .checkbox-group input[type="checkbox"] {
        margin-right: 0.5rem;
        cursor: pointer;
    }
    .checkbox-group label {
        cursor: pointer;
        font-weight: 400;
        color: #4b5563;
    }
    .btn {
        padding: 0.5rem 1rem;
        border-radius: 0.375rem;
        font-size: 0.875rem;
        font-weight: 500;
        transition: all 0.2s ease;
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        border: none;
    }
    .btn-primary {
        background-color: #3b82f6;
        color: white;
    }
    .btn-primary:hover {
        background-color: #2563eb;
        transform: translateY(-1px);
    }
    .btn-outline {
        background-color: white;
        color: #374151;
        border: 1px solid #e5e7eb;
    }
    .btn-outline:hover {
        background-color: #f9fafb;
        border-color: #d1d5db;
    }
    .btn-success {
        background-color: #10b981;
        color: white;
    }
    .btn-success:hover {
        background-color: #059669;
    }
    .p-5 {
        padding: 1.25rem;
    }
    .mb-6 {
        margin-bottom: 1.5rem;
    }
    .mt-4 {
        margin-top: 1rem;
    }
    .flex {
        display: flex;
    }
    .flex-col {
        flex-direction: column;
    }
    .md\:flex-row {
        flex-direction: row;
    }
    .md\:items-center {
        align-items: center;
    }
    .md\:justify-between {
        justify-content: space-between;
    }
    .gap-2 {
        gap: 0.5rem;
    }
    .gap-3 {
        gap: 0.75rem;
    }
    .gap-4 {
        gap: 1rem;
    }
    .items-center {
        align-items: center;
    }
    .justify-center {
        justify-content: center;
    }
    .justify-end {
        justify-content: flex-end;
    }
    .text-sm {
        font-size: 0.875rem;
    }
    .text-2xl {
        font-size: 1.5rem;
    }
    .font-bold {
        font-weight: 700;
    }
    .font-medium {
        font-weight: 500;
    }
    .text-text-primary {
        color: #111827;
    }
    .text-text-secondary {
        color: #4b5563;
    }
    .text-text-tertiary {
        color: #9ca3af;
    }
    .text-primary {
        color: #3b82f6;
    }
    .text-success {
        color: #10b981;
    }
    .text-danger {
        color: #ef4444;
    }
    .bg-gray-50 {
        background-color: #f9fafb;
    }
    .border-t {
        border-top: 1px solid #e5e7eb;
    }
    .alert {
        padding: 1rem;
        border-radius: 0.375rem;
        margin-bottom: 1rem;
    }
    .alert-success {
        background-color: #d1fae5;
        color: #065f46;
        border: 1px solid #a7f3d0;
    }
    .alert-error {
        background-color: #fee2e2;
        color: #991b1b;
        border: 1px solid #fecaca;
    }
    .password-strength {
        height: 4px;
        margin-top: 0.5rem;
        border-radius: 2px;
        background-color: #e5e7eb;
        overflow: hidden;
    }
    .password-strength-bar {
        height: 100%;
        transition: width 0.3s ease, background-color 0.3s ease;
        background-color: #ef4444;
    }
    .password-strength-text {
        font-size: 0.75rem;
        margin-top: 0.25rem;
        color: #6b7280;
    }
    .password-strength-weak .password-strength-bar {
        width: 33%;
        background-color: #ef4444;
    }
    .password-strength-medium .password-strength-bar {
        width: 66%;
        background-color: #f59e0b;
    }
    .password-strength-strong .password-strength-bar {
        width: 100%;
        background-color: #10b981;
    }
    .password-strength-weak .password-strength-text {
        color: #ef4444;
    }
    .password-strength-medium .password-strength-text {
        color: #f59e0b;
    }
    .password-strength-strong .password-strength-text {
        color: #10b981;
    }
    .password-toggle {
        position: absolute;
        right: 10px;
        top: 50%;
        transform: translateY(-50%);
        cursor: pointer;
        color: #9ca3af;
    }
    .password-toggle:hover {
        color: #6b7280;
    }
    .relative {
        position: relative;
    }
    /* 权限组样式 */
    .permissions-section {
        background-color: #f9fafb;
        border-radius: 0.375rem;
        padding: 1rem;
        margin-top: 1.5rem;
    }
    .permissions-section h3 {
        margin-top: 0;
        margin-bottom: 1rem;
        font-size: 1rem;
        font-weight: 600;
    }
    /* 响应式设计 */
    @media (max-width: 768px) {
        .form-container {
            max-width: 100%;
            padding: 0 1rem;
        }
        .btn {
            font-size: 0.75rem;
            padding: 0.375rem 0.75rem;
        }
    }
</style>
{% endblock %}

{% block content %}
    <div class="form-container">
        <!-- 页面标题和面包屑 -->
        <div class="mb-6">
            <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
                <div>
                    <div class="flex items-center text-sm text-text-tertiary mb-1">
                        <a href="/" class="hover:text-primary">首页</a>
                        <span class="mx-2">/</span>
                        <a href="{% url 'accounts:user_list' %}" class="hover:text-primary">用户管理</a>
                        <span class="mx-2">/</span>
                        <span>{% if object %}编辑用户{% else %}创建用户{% endif %}</span>
                    </div>
                    <h2 class="text-2xl font-bold">{% if object %}编辑用户{% else %}创建用户{% endif %}</h2>
                </div>
                <div class="flex gap-3">
                    <a href="{% url 'accounts:user_list' %}" class="btn btn-outline" data-toggle="tooltip" title="返回用户列表">
                        <i class="fas fa-arrow-left mr-2"></i>返回列表
                    </a>
                </div>
            </div>
        </div>
        
        <!-- 消息提示 -->
        {% if messages %}
            {% for message in messages %}
                <div class="alert alert-{{ message.tags }}" role="alert">
                    <div class="flex items-center">
                        {% if message.tags == 'success' %}
                            <i class="fas fa-check-circle mr-2"></i>
                        {% elif message.tags == 'error' %}
                            <i class="fas fa-exclamation-circle mr-2"></i>
                        {% endif %}
                        {{ message }}
                    </div>
                </div>
            {% endfor %}
        {% endif %}
        
        <!-- 表单卡片 -->
        <div class="card">
            <div class="p-5">
                <form method="post" class="user-form" novalidate>
                    {% csrf_token %}
                    
                    <!-- 错误提示区域 -->
                    {% if form.errors %}
                        <div class="alert alert-error mb-4">
                            <div class="flex items-center mb-2">
                                <i class="fas fa-exclamation-circle mr-2"></i>
                                <span class="font-medium">表单存在以下错误：</span>
                            </div>
                            <ul class="list-disc pl-6 text-sm">
                                {% for field in form %}
                                    {% for error in field.errors %}
                                        <li>{{ field.label }}: {{ error }}</li>
                                    {% endfor %}
                                {% endfor %}
                                {% for error in form.non_field_errors %}
                                    <li>{{ error }}</li>
                                {% endfor %}
                            </ul>
                        </div>
                    {% endif %}
                    
                    <!-- 基本信息字段组 -->
                    <div class="mb-6">
                        <h3 class="font-medium text-lg mb-4 text-text-primary">基本信息</h3>
                        
                        <!-- 用户名字段 -->
                        <div class="form-group">
                            <label for="{{ form.username.id_for_label }}" class="form-label">
                                用户名 <span class="text-danger">*</span>
                            </label>
                            <input
                                type="text"
                                id="{{ form.username.id_for_label }}"
                                name="{{ form.username.name }}"
                                value="{{ form.username.value|default:'' }}"
                                class="form-control{% if form.username.errors %} error{% endif %}"
                                placeholder="请输入用户名"
                                {% if form.username.field.required %}required{% endif %}
                            >
                            {% if form.username.errors %}
                                {% for error in form.username.errors %}
                                    <div class="form-error">{{ error }}</div>
                                {% endfor %}
                            {% endif %}
                        </div>
                        
                        <!-- 邮箱字段 -->
                        <div class="form-group">
                            <label for="{{ form.email.id_for_label }}" class="form-label">
                                邮箱 <span class="text-danger">*</span>
                            </label>
                            <input
                                type="email"
                                id="{{ form.email.id_for_label }}"
                                name="{{ form.email.name }}"
                                value="{{ form.email.value|default:'' }}"
                                class="form-control{% if form.email.errors %} error{% endif %}"
                                placeholder="请输入邮箱地址"
                                {% if form.email.field.required %}required{% endif %}
                            >
                            {% if form.email.errors %}
                                {% for error in form.email.errors %}
                                    <div class="form-error">{{ error }}</div>
                                {% endfor %}
                            {% endif %}
                        </div>
                        
                        <!-- 密码字段 - 仅在创建新用户或编辑模式下启用 -->
                        {% if not object or form.instance.pk and 'password' in form.fields %}
                            <div class="form-group">
                                <label for="{{ form.password1.id_for_label }}" class="form-label">
                                    密码 {% if not object %}<span class="text-danger">*</span>{% endif %}
                                </label>
                                <div class="relative">
                                    <input
                                        type="password"
                                        id="{{ form.password1.id_for_label }}"
                                        name="{{ form.password1.name }}"
                                        class="form-control{% if form.password1.errors %} error{% endif %}"
                                        placeholder="请输入密码"
                                        {% if not object %}required{% endif %}
                                    >
                                    <span class="password-toggle" id="toggle-password1">
                                        <i class="fas fa-eye"></i>
                                    </span>
                                </div>
                                {% if not object %}
                                    <div class="password-strength" id="password-strength1">
                                        <div class="password-strength-bar"></div>
                                    </div>
                                    <div class="password-strength-text" id="password-strength-text1">
                                        密码强度: 未输入
                                    </div>
                                {% endif %}
                                {% if form.password1.errors %}
                                    {% for error in form.password1.errors %}
                                        <div class="form-error">{{ error }}</div>
                                    {% endfor %}
                                {% endif %}
                            </div>
                            
                            <div class="form-group">
                                <label for="{{ form.password2.id_for_label }}" class="form-label">
                                    确认密码 {% if not object %}<span class="text-danger">*</span>{% endif %}
                                </label>
                                <div class="relative">
                                    <input
                                        type="password"
                                        id="{{ form.password2.id_for_label }}"
                                        name="{{ form.password2.name }}"
                                        class="form-control{% if form.password2.errors %} error{% endif %}"
                                        placeholder="请再次输入密码"
                                        {% if not object %}required{% endif %}
                                    >
                                    <span class="password-toggle" id="toggle-password2">
                                        <i class="fas fa-eye"></i>
                                    </span>
                                </div>
                                {% if form.password2.errors %}
                                    {% for error in form.password2.errors %}
                                        <div class="form-error">{{ error }}</div>
                                    {% endfor %}
                                {% endif %}
                            </div>
                        {% endif %}
                    </div>
                    
                    <!-- 权限设置字段组 -->
                    <div class="permissions-section">
                        <h3 class="font-medium text-text-primary">权限设置</h3>
                        
                        <!-- 激活状态复选框 -->
                        <div class="checkbox-group">
                            <input
                                type="checkbox"
                                id="{{ form.is_active.id_for_label }}"
                                name="{{ form.is_active.name }}"
                                {% if form.is_active.value %}checked{% endif %}
                            >
                            <label for="{{ form.is_active.id_for_label }}">
                                激活用户
                            </label>
                        </div>
                        
                        <!-- 管理员权限复选框 -->
                        <div class="checkbox-group">
                            <input
                                type="checkbox"
                                id="{{ form.is_staff.id_for_label }}"
                                name="{{ form.is_staff.name }}"
                                {% if form.is_staff.value %}checked{% endif %}
                            >
                            <label for="{{ form.is_staff.id_for_label }}">
                                授予管理员权限
                            </label>
                        </div>
                        
                        <!-- 超级用户权限复选框 -->
                        <div class="checkbox-group">
                            <input
                                type="checkbox"
                                id="{{ form.is_superuser.id_for_label }}"
                                name="{{ form.is_superuser.name }}"
                                {% if form.is_superuser.value %}checked{% endif %}
                            >
                            <label for="{{ form.is_superuser.id_for_label }}">
                                授予超级用户权限
                            </label>
                        </div>
                    </div>
                    
                    <!-- 操作按钮 -->
                    <div class="mt-6 flex gap-3 justify-end">
                        <a href="{% url 'accounts:user_list' %}" class="btn btn-outline cancel-button">
                            <i class="fas fa-times mr-2"></i>取消
                        </a>
                        <button type="submit" class="btn btn-primary submit-button">
                            <i class="fas fa-save mr-2"></i>
                            {% if object %}更新用户{% else %}创建用户{% endif %}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
{% endblock %}

{% block extra_js %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 表单提交处理
        const form = document.querySelector('.user-form');
        const submitButton = document.querySelector('.submit-button');
        
        if (form) {
            form.addEventListener('submit', function(e) {
                // 添加表单提交加载状态
                submitButton.disabled = true;
                submitButton.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>处理中...';
                
                // 表单验证
                let isValid = true;
                const requiredFields = form.querySelectorAll('[required]');
                
                requiredFields.forEach(field => {
                    if (!field.value.trim()) {
                        isValid = false;
                        field.classList.add('error');
                        // 添加错误提示（如果没有）
                        const errorElement = field.parentElement.querySelector('.form-error');
                        if (!errorElement) {
                            const newError = document.createElement('div');
                            newError.className = 'form-error';
                            newError.textContent = '此字段为必填项';
                            field.parentElement.appendChild(newError);
                        }
                    } else {
                        field.classList.remove('error');
                        // 移除错误提示
                        const errorElement = field.parentElement.querySelector('.form-error');
                        if (errorElement) {
                            errorElement.remove();
                        }
                    }
                });
                
                // 邮箱格式验证
                const emailField = form.querySelector('input[type="email"]');
                if (emailField) {
                    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                    if (emailField.value.trim() && !emailRegex.test(emailField.value.trim())) {
                        isValid = false;
                        emailField.classList.add('error');
                        let errorElement = emailField.parentElement.querySelector('.form-error');
                        if (!errorElement || !errorElement.textContent.includes('邮箱格式不正确')) {
                            if (errorElement) {
                                errorElement.textContent = '邮箱格式不正确';
                            } else {
                                const newError = document.createElement('div');
                                newError.className = 'form-error';
                                newError.textContent = '邮箱格式不正确';
                                emailField.parentElement.appendChild(newError);
                            }
                        }
                    }
                }
                
                // 密码匹配验证
                const password1Field = document.getElementById('{{ form.password1.id_for_label }}');
                const password2Field = document.getElementById('{{ form.password2.id_for_label }}');
                
                if (password1Field && password2Field && password1Field.value && password2Field.value) {
                    if (password1Field.value !== password2Field.value) {
                        isValid = false;
                        password2Field.classList.add('error');
                        let errorElement = password2Field.parentElement.querySelector('.form-error');
                        if (!errorElement || !errorElement.textContent.includes('两次输入的密码不一致')) {
                            if (errorElement) {
                                errorElement.textContent = '两次输入的密码不一致';
                            } else {
                                const newError = document.createElement('div');
                                newError.className = 'form-error';
                                newError.textContent = '两次输入的密码不一致';
                                password2Field.parentElement.appendChild(newError);
                            }
                        }
                    }
                }
                
                if (!isValid) {
                    e.preventDefault();
                    submitButton.disabled = false;
                    submitButton.innerHTML = '<i class="fas fa-save mr-2"></i>{% if object %}更新用户{% else %}创建用户{% endif %}';
                    
                    // 滚动到第一个错误字段
                    const firstErrorField = form.querySelector('.error');
                    if (firstErrorField) {
                        firstErrorField.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        firstErrorField.focus();
                    }
                }
            });
        }
        
        // 密码显示/隐藏切换
        const passwordToggles = document.querySelectorAll('.password-toggle');
        passwordToggles.forEach(toggle => {
            toggle.addEventListener('click', function() {
                const passwordFieldId = this.id.replace('toggle-', '');
                const passwordField = document.getElementById(passwordFieldId);
                const icon = this.querySelector('i');
                
                if (passwordField.type === 'password') {
                    passwordField.type = 'text';
                    icon.classList.remove('fa-eye');
                    icon.classList.add('fa-eye-slash');
                } else {
                    passwordField.type = 'password';
                    icon.classList.remove('fa-eye-slash');
                    icon.classList.add('fa-eye');
                }
            });
        });
        
        // 密码强度检测
        const passwordStrengthElement = document.getElementById('password-strength1');
        const passwordStrengthTextElement = document.getElementById('password-strength-text1');
        
        if (passwordStrengthElement && password1Field) {
            password1Field.addEventListener('input', function() {
                const password = this.value;
                let strength = 0;
                let strengthText = '未输入';
                let strengthClass = '';
                
                if (password.length > 0) {
                    // 密码长度检查
                    if (password.length >= 8) strength += 1;
                    
                    // 包含数字检查
                    if (/\d/.test(password)) strength += 1;
                    
                    // 包含小写字母检查
                    if (/[a-z]/.test(password)) strength += 1;
                    
                    // 包含大写字母检查
                    if (/[A-Z]/.test(password)) strength += 1;
                    
                    // 包含特殊字符检查
                    if (/[^A-Za-z0-9]/.test(password)) strength += 1;
                    
                    // 确定密码强度等级
                    if (strength <= 2) {
                        strengthClass = 'password-strength-weak';
                        strengthText = '弱: 建议使用更复杂的密码';
                    } else if (strength <= 4) {
                        strengthClass = 'password-strength-medium';
                        strengthText = '中: 可以再增加一些复杂性';
                    } else {
                        strengthClass = 'password-strength-strong';
                        strengthText = '强: 密码安全性良好';
                    }
                }
                
                // 更新UI
                passwordStrengthElement.className = 'password-strength';
                if (strengthClass) {
                    passwordStrengthElement.classList.add(strengthClass);
                }
                passwordStrengthTextElement.textContent = strengthText;
            });
        }
        
        // 实时表单验证
        const formInputs = form.querySelectorAll('.form-control');
        formInputs.forEach(input => {
            input.addEventListener('input', function() {
                // 移除错误样式
                this.classList.remove('error');
                
                // 移除错误提示
                const errorElement = this.parentElement.querySelector('.form-error');
                if (errorElement) {
                    errorElement.remove();
                }
            });
        });
        
        // 按钮悬停效果增强
        const allButtons = document.querySelectorAll('.btn');
        allButtons.forEach(button => {
            if (!button.classList.contains('disabled')) {
                button.addEventListener('mouseenter', function() {
                    this.style.transform = 'translateY(-1px)';
                    this.style.boxShadow = '0 4px 6px rgba(0, 0, 0, 0.1)';
                });
                
                button.addEventListener('mouseleave', function() {
                    this.style.transform = 'translateY(0)';
                    this.style.boxShadow = 'none';
                });
                
                button.addEventListener('mousedown', function() {
                    this.style.transform = 'translateY(0)';
                });
            }
        });
        
        // 键盘快捷键
        document.addEventListener('keydown', function(e) {
            // Ctrl/Cmd + S 提交表单
            if ((e.ctrlKey || e.metaKey) && e.key === 's') {
                e.preventDefault();
                if (submitButton && !submitButton.disabled) {
                    form.dispatchEvent(new Event('submit'));
                }
            }
            
            // Esc 取消并返回列表
            if (e.key === 'Escape') {
                const cancelButton = document.querySelector('.cancel-button');
                if (cancelButton) {
                    cancelButton.click();
                }
            }
        });
        
        // 滚动时导航栏样式变化
        const header = document.querySelector('header');
        if (header) {
            window.addEventListener('scroll', function() {
                if (window.scrollY > 10) {
                    header.classList.add('shadow-md');
                } else {
                    header.classList.remove('shadow-md');
                }
            });
        }
    });
</script>
{% endblock %}

